//
//  FeedsViewModel.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/18.
//  Copyright © 2019 Hins. All rights reserved.
//

import Foundation
import RxSwift


class FeedsViewModel {
    let categoryItem: FeedsCategory.CategoryItem
    private(set) var entity: FeedsEntity?
    init(categoryItem: FeedsCategory.CategoryItem) {
        self.categoryItem = categoryItem
    }
}

extension FeedsViewModel {
    var feeds: [FeedItem] {
        return entity?.feeds ?? []
    }
    
    var fid: String {
        return entity?.fid ?? categoryItem.fid
    }
    
    var currentPageIndex: Int32 {
        return entity?.currentPageIndex ?? 0
    }
    
    var totalPageCount: Int32 {
        return entity?.totalPageCount ?? 0
    }
    
    var isTheLastPage: Bool {
        return currentPageIndex >= totalPageCount
    }
}

extension FeedsViewModel {
    func fetchLatestData() -> Observable<Event<FeedsEntity>> {
        return Network.loadFeeds(FeedsEntityRequest.build(categoryItem.fid, 0, AccountManager.share.user.uid))
            .preDo(onNext: { self.entity = $0 })
            .observeOn(MainScheduler.asyncInstance)
    }
    
    func loadMoreData() -> Observable<Event<FeedsEntity>> {
        guard let entity = entity else { fatalError() }
        return Network.loadFeeds(FeedsEntityRequest.build(categoryItem.fid,
                                                          currentPageIndex + 1,
                                                          AccountManager.share.user.uid))
            .preDo(onNext: { (e) in
                var new = e
                new.feeds = entity.feeds + e.feeds
                self.entity = new
            })
            .observeOn(MainScheduler.asyncInstance)
    }
}

private extension FeedsEntityRequest {
    static func build(_ fid: String, _ page: Int32, _ uid: String) -> FeedsEntityRequest {
        return FeedsEntityRequest.with {
            $0.fid = fid
            $0.page = page
            $0.uid = uid
        }
    }
}
